const express = require('express')
const router = express.Router()
const humps = require('humps')
const db = require('../../database/db')

const getLastDay = (y, m) => {
    let dt = new Date(y, m, 1)
    cdt = new Date(dt.getTime() - 1000 * 60 * 60 * 24)
    return cdt.getDate()
}

const getPlanTime = (from, to) => {
    const from_y = from.split('-')[0]
    const to_y = to.split('-')[0]
    const from_m = from.split('-')[1]
    const to_m = to.split('-')[1]
    const res_to = `${to_y}-${to_m}-${getLastDay(to_y, +to_m)}`
    if (from_m === to_m) { // 同一个月的时候
        return { from: `${from_y}-${from_m}-01`, to: res_to }
    } else {
        return { from: `${from_y}-${from_m}-01`, to: res_to }
    }
}

const concatScreenSql = (table, data, type, str) => {
    if (data.length) {
        data.forEach((item, i) => {
            if (i < data.length - 1) {
                str += '' + table + '.`name` = "' + item[type] + '" OR '
            } else {
                str += '' + table + '.`name` = "' + item[type] + '" )'
            }
        })
    } else {
        str = ''
    }
    return str
}
module.exports = (() => {
    router.get('/screenDepts', async (req, res, next) => {
        try {
            const doc = humps.camelizeKeys(await db.getScreenDepts())
            res.send(doc)
        } catch (err) {
            next(err)
        }
    })

    router.post('/screenPlanLT', async (req, res, next) => {
        try {
            let str = ''
            const _visits = humps.camelizeKeys(await db.getScreenRecordLT({ from: req.body.from, to: req.body.to, sql: str, time: 'time' }))
            str = 'r.`is_sign` = 1 AND '
            const _signs = humps.camelizeKeys(await db.getScreenRecordLT({ from: req.body.from, to: req.body.to, sql: str, time: 'time' }))
            str = 'r.`is_pick_car` = 1 AND r.`pick_car_time` != "" AND '
            const _picks = humps.camelizeKeys(await db.getScreenRecordLT({ from: req.body.from, to: req.body.to, sql: str, time: 'pick_car_time' }))
            const _plans = humps.camelizeKeys(await db.getScreen({ from: getPlanTime(req.body.from, req.body.to).from, to: getPlanTime(req.body.from, req.body.to).to }))
            let visitPlan = 0
            let signPlan = 0
            let visit = 0
            let sign = 0
            let pick = 0
            _plans.forEach(item => {
                visitPlan += +item.visitPlan
                signPlan += +item.signPlan
            });
            _visits.forEach(item => {
                visit += +item.amount;
            });
            _signs.forEach(item => {
                sign += +item.amount;
            });
            _picks.forEach(item => {
                pick += +item.amount;
            });
            res.send({
                visitPlan,
                signPlan,
                visit,
                sign,
                pick
            })
        } catch (err) {
            next(err)
        }
    })

    router.post('/screenPlanLC', async (req, res, next) => {
        try {
            const arr2obj = arr => {
                const obj = {};
                arr.forEach(item => {
                    obj[item.salesmanName] = item.amount;
                });
                return obj;
            };
            let str = 'AND ( '
            const _visits = humps.camelizeKeys(await db.getScreenLC({ from: req.body.from, to: req.body.to, sql: '', select: '' }))
            const _signs = arr2obj(humps.camelizeKeys(await db.getScreenLC({ from: req.body.from, to: req.body.to, sql: 'r.`is_sign` = 1 AND ', select: await concatScreenSql('s', _visits, 'salesmanName', str) })))
            const name = []
            const visits = []
            const signs = []
            _visits.reverse().forEach(item => {
                item.signs = _signs[item.salesmanName] || 0
                name.push(item.salesmanName);
                visits.push(item.amount);
                signs.push(item.signs);
            });
            res.send({ name, visits, signs })
        } catch (err) {
            next(err)
        }
    })

    router.post('/screenPlanRC', async (req, res, next) => {
        try {
            const arr2obj = arr => {
                const obj = {};
                arr.forEach(item => {
                    obj[item.warrantMan] = item.amount;
                });
                return obj;
            };
            const _ordertakings = arr2obj(humps.camelizeKeys(await db.getScreenRC({ from: req.body.from, to: req.body.to, sql: '', time: 'time' })))
            const _passs = arr2obj(humps.camelizeKeys(await db.getScreenRC({ from: req.body.from, to: req.body.to, sql: 'r.`pass_time` != "" AND ', time: 'pass_time' })))
            const names = humps.camelizeKeys(await db.getWarrantMansNames())
            const yAxis = []
            const ordertakings = []
            const passs = []
            names.forEach((item, i) => {
                yAxis.push(item.name)
                ordertakings.push(_ordertakings[item.name] || 0)
                passs.push(_passs[item.name] || 0)
            });
            res.send({ yAxis: yAxis.reverse(), ordertakings: ordertakings.reverse(), passs: passs.reverse() })
        } catch (err) {
            next(err)
        }
    })

    router.post('/screenPlanRB', async (req, res, next) => {
        try {
            const arr2obj = (arr) => {
                const obj = {}
                arr.forEach(itm => {
                    const time = itm.time.split('-')
                    obj[time[time.length - 1]] = itm.amount
                })
                return obj
            }
            let str = ''
            const _visits = await db.getScreenRecordRB({ from: req.body.from, to: req.body.to, sql: '' })
            str += 'AND r.`is_sign` = 1'
            const _signs = await db.getScreenRecordRB({ from: req.body.from, to: req.body.to, sql: str })
            str += ' AND r.`is_pick_car` = 1'
            const _picks = await db.getScreenRecordPicksRB({ from: req.body.from, to: req.body.to, sql: str })
            const nowDay = req.body.filterTime.split("-")[2]
            const xaxis = []
            const visits = []
            const signs = []
            const picks = []

            for (var i = 1; i <= nowDay; i++) {
                const key = i < 10 ? `0${i}` : `${i}`;
                visits.push(arr2obj(_visits)[key] || 0);
                signs.push(arr2obj(_signs)[key] || 0);
                picks.push(arr2obj(_picks)[key] || 0);
                xaxis.push(key);
            }
            res.send({
                xaxis,
                visits,
                signs,
                picks
            })
        } catch (err) {
            next(err)
        }
    })

    router.post('/screenPlanRT', async (req, res, next) => {
        try {
            let str = ''
            const _visits = humps.camelizeKeys(await db.getScreenRecordRT({ from: req.body.from, to: req.body.to, sql: '', time: 'time' }))
            str = 'r.`is_sign` = 1 AND '
            const _signs = humps.camelizeKeys(await db.getScreenRecordRT({ from: req.body.from, to: req.body.to, sql: str, time: 'time' }))
            str = 'r.`is_pick_car` = 1 AND '
            const _picks = humps.camelizeKeys(await db.getScreenRecordRT({ from: req.body.from, to: req.body.to, sql: str, time: 'pick_car_time' }))
            const visits = []
            const signs = []
            const picks = []
            const legend = []
            _visits.forEach(item => {
                legend.push(item.name);
                visits.push({
                    value: item.amount,
                    name: item.name
                });
            });
            _signs.forEach(item => {
                signs.push({
                    value: item.amount,
                    name: item.name
                });
            });
            _picks.forEach(item => {
                picks.push({
                    value: item.amount,
                    name: item.name
                });
            });
            res.send({
                visits,
                signs,
                picks,
                legend
            })
        } catch (err) {
            next(err)
        }
    })

    router.post('/screenSphere', async (req, res, next) => {
        try {
            let str = ''
            const visits = humps.camelizeKeys(await db.getScreenSphere({ from: req.body.from, to: req.body.to, sql: '', time: 'r.`time`' }))
            str += 'r.`is_sign` = 1 AND '
            const signs = humps.camelizeKeys(await db.getScreenSphere({ from: req.body.from, to: req.body.to, sql: str, time: 'r.`time`' }))
            str += 'r.`is_pick_car` = 1 AND '
            const picks = humps.camelizeKeys(await db.getScreenSphere({ from: req.body.from, to: req.body.to, sql: str, time: 'r.`pick_car_time`' }))
            const data = []
            const arr = [
                ...visits.map(item => {
                    item.type = "上门";
                    return item;
                }),
                ...signs.map(item => {
                    item.type = "签单";
                    return item;
                }),
                ...picks.map(item => {
                    item.type = "提车";
                    return item;
                })
            ];
            arr.sort(() => {
                return 0.5 - Math.random();
            });
            arr.forEach((item, i) => {
                if (item.type === "上门") {
                    data.push(
                        item.salesmanName,
                        "上门",
                        `(${item.amount})`,
                        i + 1,
                        i + 1
                    );
                }
                if (item.type === "签单") {
                    data.push(
                        item.salesmanName,
                        "签单",
                        `(${item.amount})`,
                        i + 1,
                        i + 1
                    );
                }
                if (item.type === "提车") {
                    data.push(
                        item.salesmanName,
                        "提车",
                        `(${item.amount})`,
                        i + 1,
                        i + 1
                    );
                }
            });
            res.send(data)
        } catch (err) {
            next(err)
        }
    })

    router.post('/screenPlanLB', async (req, res, next) => {
        try {
            const filter_repeat = (plans, type) => {
                let obj = {}
                plans.forEach((item) => {
                    let key = '' + item.centerId + item.departmentId
                    if (obj[key]) {
                        obj[key][type] += item[type]
                    } else {
                        obj[key] = item
                    }
                })
                return Object.values(obj)
            }

            let str = ''
            let _plans = humps.camelizeKeys(await db.getStats_plansOfDept({ from: getPlanTime(req.body.from, req.body.to).from, to: getPlanTime(req.body.from, req.body.to).to, sql: '' }))
            const _visits = humps.camelizeKeys(await db.getStats_RateOfDept({ from: req.body.from, to: req.body.to, sql: '' }))
            str = 'r.`is_sign` = 1 AND '
            const _signs = humps.camelizeKeys(await db.getStats_RateOfDept({ from: req.body.from, to: req.body.to, sql: str }))
            let _completeV = []
            let _completeS = []
            let _planV = []
            let _planS = []
            const xAxis = []
            const completeV = []
            const completeS = []
            const planV = []
            const planS = []
            _visits.forEach(item => {
                _completeV.push({
                    amount: item.amount,
                    x: `${item.centerName}${item.deptName}`
                })
            })
            _signs.forEach(item => {
                _completeS.push({
                    amount: item.amount,
                    x: `${item.centerName}${item.deptName}`
                })
            })
            _plans = filter_repeat(_plans, 'signPlan')
            _plans.forEach(item => {
                _planV.push({
                    amount: item.visitPlan,
                    x: `${item.centerName}${item.deptName}`
                })
                _planS.push({
                    amount: item.signPlan,
                    x: `${item.centerName}${item.deptName}`
                })
            })
            const arr2obj = arr => {
                const obj = {}
                arr.forEach(itm => {
                    obj[itm.x] = itm.amount
                })
                return obj
            }
            _completeV = arr2obj(_completeV)
            _completeS = arr2obj(_completeS)
            _planV = arr2obj(_planV)
            _planS = arr2obj(_planS)

            for (var i = 0; i < req.body.xAxis.length; i++) {
                const key = req.body.xAxis[i]
                planV.push(_planV[key] || 0)
                planS.push(_planS[key] || 0)
                completeV.push(_completeV[key] || 0)
                completeS.push(_completeS[key] || 0)
                xAxis.push(key)
            }
            res.send({
                xAxis,
                completeV,
                completeS,
                planV,
                planS
            })
        } catch (err) {
            next(err)
        }
    })


    return router
})();